/* 
 * The MIT License
 *
 * Copyright 2014 Venkat Ram Akkineni.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.netbeans.modules.tfsnb.tfvc.workspace;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import org.netbeans.modules.tfsnb.tfvc.LinkButton;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;

/**
 *
 * @author Venkat Ram Akkineni
 */
public class ConfiguredWorkspacesTablePanel extends javax.swing.JPanel {

    /**
     * Creates new form ConfiguredWorkspacesTablePanel
     */
    public ConfiguredWorkspacesTablePanel(WorkspacesMultiView view) {
        initComponents();
        this.view = view;
    }
    
    public void postConstruct() {
        tableModel = new ConfiguredWorkspacesTablePanelModel(view);
        ListSelectionModel listSelectionModel = workspacesTable.getSelectionModel();
        listSelectionModel.addListSelectionListener(new ListSelectionListener(){

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if(e.getValueIsAdjusting() && workspacesTable.getSelectedRows().length == 1) {
                    showWorkspaceDetailsPanel(workspacesTable.getSelectedRows());
                }
            }
            
        });
        workspacesTable.setModel(tableModel);
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
     * content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        workspacesSplitPane = new javax.swing.JSplitPane();
        workspacesPanel = new javax.swing.JPanel();
        workspacesTableScrollPane = new javax.swing.JScrollPane();
        workspacesTable = new javax.swing.JTable();
        detailsPanel = new javax.swing.JPanel();

        workspacesSplitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        workspacesTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Computer", "Comment"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        workspacesTableScrollPane.setViewportView(workspacesTable);

        javax.swing.GroupLayout workspacesPanelLayout = new javax.swing.GroupLayout(workspacesPanel);
        workspacesPanel.setLayout(workspacesPanelLayout);
        workspacesPanelLayout.setHorizontalGroup(
            workspacesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(workspacesPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(workspacesTableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 1034, Short.MAX_VALUE)
                .addContainerGap())
        );
        workspacesPanelLayout.setVerticalGroup(
            workspacesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(workspacesPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(workspacesTableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
                .addContainerGap())
        );

        workspacesSplitPane.setTopComponent(workspacesPanel);

        detailsPanel.setLayout(new java.awt.BorderLayout());
        workspacesSplitPane.setRightComponent(detailsPanel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(workspacesSplitPane)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(workspacesSplitPane)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    public JToolBar getToolBar() {
        JToolBar toolbar = new JToolBar();
        addButtons(toolbar);
        return toolbar;
    }
    
    private void addButtons(JToolBar toolbar) {        
        JButton add = createButton("plus.png", "ConfiguredWorkspacesTablePanel.addWorkspace", "ConfiguredWorkspacesTablePanel.addWorkspace");
        add.addActionListener(addAction);
        toolbar.add(add);
        
        JButton remove = createButton("minus.png", "ConfiguredWorkspacesTablePanel.removeWorkspace", "ConfiguredWorkspacesTablePanel.removeWorkspace");
        remove.addActionListener(removeAction);
        toolbar.add(remove);
        
        JButton edit = createButton("edit.png", "ConfiguredWorkspacesTablePanel.editWorkspace", "ConfiguredWorkspacesTablePanel.editWorkspace");
        edit.addActionListener(editAction);
        toolbar.add(edit);
        
        JButton refresh = createButton("refresh.png", "ConfiguredWorkspacesTablePanel.refreshList", "ConfiguredWorkspacesTablePanel.refreshList");
        refresh.addActionListener(refreshAction);
        toolbar.add(refresh);
    }
    
    /**
     * 
     * @param iconBase
     * @param altTextKey
     * @param tooltipTextKey
     * @return 
     */
    private JButton createButton(final String iconBase, final String altTextKey, final String tooltipTextKey) {
        JButton button = new JButton();
        
        String altText = NbBundle.getMessage(ConfiguredWorkspacesTablePanel.class, altTextKey);
        String tooltipText = NbBundle.getMessage(ConfiguredWorkspacesTablePanel.class, tooltipTextKey);
        ImageIcon icon = ImageUtilities.loadImageIcon(RESOURCE_DIR + iconBase, true);
        if(icon != null) {
            button.setIcon(icon);
        } else {
            button.setText(altText);
        }
        button.setToolTipText(altText);
        return button;
    }
    
    
    private void showAddWorkspacePanels() {
                
        SwingUtilities.invokeLater(new Runnable(){
            
            @Override
            public void run() {
                switchPanel = new SwitchPanel();
                WorkspaceSimpleFormPanel simplePanel = new WorkspaceSimpleFormPanel();
                WorkspaceAdvancedFormPanel advancedPanel = new WorkspaceAdvancedFormPanel();
                LinkButton simpleButton = createLinkButton("ConfiguredWorkspacesTablePanel.SwitchPanel.simpleButtonNormalText", 
                        "ConfiguredWorkspacesTablePanel.SwitchPanel.simpleButtonHoverText", "SimplePanel");
                
                PropertyChangeListener removeWorkspaceFormPanelChangeListener = new PropertyChangeListener(){
                    @Override
                    public void propertyChange(PropertyChangeEvent evt) {
                        if(evt.getPropertyName().equals("removeAddWorkspacePanel")) {
                            
                            if(!((boolean) evt.getNewValue())) {
                                detailsPanel.removeAll();
                                detailsPanel.updateUI();
                                switchPanel = null;
                            }
                        }
                    }
                };
                
                simplePanel.addPropertyChangeListener(removeWorkspaceFormPanelChangeListener);
                switchPanel.add(simpleButton, simplePanel);

                LinkButton advancedButton = createLinkButton("ConfiguredWorkspacesTablePanel.SwitchPanel.advancedButtonNormalText", 
                        "ConfiguredWorkspacesTablePanel.SwitchPanel.advancedButtonHoverText", "AdvancedPanel");
                advancedPanel.addPropertyChangeListener(removeWorkspaceFormPanelChangeListener);
                switchPanel.add(advancedButton, advancedPanel);
                detailsPanel.add(switchPanel, BorderLayout.CENTER);
                detailsPanel.revalidate();
                detailsPanel.updateUI();
            }
            
        });        
    }
    
    private void showWorkspaceDetailsPanel(final int[] selectedRows) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                String displayName = (String) workspacesTable.getModel().getValueAt(selectedRows[0], 0);
                
                if(workingFoldersMappingsPanel == null) {
                    workingFoldersMappingsPanel = new WorkingFoldersMappingsPanel(view.getVersionControlClient(), 
                            view.getTeamProjectCollection(),
                            displayName);
                } else {
                    workingFoldersMappingsPanel.reRenderTable(displayName);
                }
                
                if(!detailsPanel.isAncestorOf(workingFoldersMappingsPanel)) {
                    detailsPanel.add(workingFoldersMappingsPanel);
                    detailsPanel.revalidate();
                    detailsPanel.updateUI();
                }
            }
        });
        
    }
    
    private LinkButton createLinkButton(String normalTextKey, String hoverTextKey, String name) {
        return new LinkButton(NbBundle.getMessage(ConfiguredWorkspacesTablePanel.class, normalTextKey), 
        NbBundle.getMessage(ConfiguredWorkspacesTablePanel.class, hoverTextKey), switchPanel, name);
    }

    private WorkingFoldersMappingsPanel workingFoldersMappingsPanel;
    private SwitchPanel switchPanel;
    private static final String RESOURCE_DIR = "org/netbeans/modules/tfsnb/tfvc/workspace/";    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel detailsPanel;
    private javax.swing.JPanel workspacesPanel;
    private javax.swing.JSplitPane workspacesSplitPane;
    private javax.swing.JTable workspacesTable;
    private javax.swing.JScrollPane workspacesTableScrollPane;
    // End of variables declaration//GEN-END:variables
    private WorkspacesMultiView view;
    private DefaultTableModel tableModel;

    private static class ConfiguredWorkspacesTablePanelModel extends DefaultTableModel {

        public ConfiguredWorkspacesTablePanelModel(final WorkspacesMultiView view) {
            super(view.getWorkspacesData(),
            new String [] {
                NbBundle.getMessage(ConfiguredWorkspacesTablePanel.class, "ConfiguredWorkspacesTablePanel.Table.name"), 
                NbBundle.getMessage(ConfiguredWorkspacesTablePanel.class, "ConfiguredWorkspacesTablePanel.Table.computer"), 
                NbBundle.getMessage(ConfiguredWorkspacesTablePanel.class, "ConfiguredWorkspacesTablePanel.Table.comment")
            });
        }        

        @Override
        public int getColumnCount() {
            return 3;
        }
        
        Class[] types = new Class [] {
            java.lang.String.class, java.lang.String.class, java.lang.String.class
        };

        @Override
        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }
        
    }
    
    final ActionListener addAction = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            showAddWorkspacePanels();
        }
        
    };
    
    final ActionListener removeAction = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            view.remove();
        }
        
    };
    
    final ActionListener editAction = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            view.save();
        }
        
    };
    
    final ActionListener refreshAction = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            tableModel.setRowCount(0);
            
            Object[][] data = view.getWorkspacesData();
            
            for(int i = 0; i < data.length; i++) {
                Object[] row = data[i];
                tableModel.addRow(row);
            }
        }
        
    };

}
